import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class DioCase extends StatefulWidget {
  const DioCase({Key? key}) : super(key: key);

  @override
  _DioCaseState createState() => _DioCaseState();
}

class _DioCaseState extends State<DioCase> {
  List _channels = []; // _的前缀表示私有的，不能在类外访问 私有的作用是避免变量被修改

  // 相当于鸿蒙中的aboutToAppear
  @override
  void initState() {
    // 发起请求
    getAllChannels();
    super.initState();
  }

  getAllChannels() async {
    String BASE_URL = 'https://geek.itheima.net'; // 请求基础地址
    Dio dio = Dio(); // 创建请求实例
    var res = await dio.get('$BASE_URL/v1_0/channels'); // 发起请求
    setState(() {
      _channels = res.data['data']['channels'] as List;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GridView(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4, crossAxisSpacing: 10, mainAxisSpacing: 10),
      children: _channels.map((dynamic item) {
        return Container(
          color: Colors.blue,
          alignment: Alignment.center,
          margin: const EdgeInsets.all(10),
          child: Text(
            item['name'],
            style: const TextStyle(fontSize: 20, color: Colors.white),
          ),
        );
      }).toList(),
    );
  }
}
